package sudoku.server.persistencia.filesystem;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Vector;

import sudoku.server.dominio.Tablero;
import sudoku.server.persistencia.TableroDAO;

public class TableroDAOFS extends TableroDAO {
	private String path;

	public TableroDAOFS(Tablero tablero, String ubicaciontableros) {
		super(tablero);
		if (!ubicaciontableros.endsWith("/"))
			ubicaciontableros+="/";
		this.path=ubicaciontableros;
	}

	@Override
	public void getTablero(String id) throws Exception {
		String fileName=this.path + "tablero" + id + ".txt";
		FileInputStream fi=new FileInputStream(fileName);
		byte[] b=new byte[fi.available()];
		fi.read(b);
		fi.close();
		String ristra=new String(b);
		this.tablero.setId(Integer.parseInt(id));
		this.tablero.setNumeros(ristra);
		this.tablero.crearVectorDeJugadores();

	}

	@Override
	public void insert(String ristra) throws Exception {
		FiltroFicheros filtro=new FiltroFicheros();
		Vector<String> ficheros=filtro.loadFiles(this.path);
		int maximo=Integer.MIN_VALUE;
		for (String s : ficheros) {
			String sNumero=s.substring(7, s.indexOf("."));
			int numero=Integer.parseInt(sNumero);
			if (numero>maximo)
				maximo=numero;
		}
		maximo+=1;
		FileOutputStream fos=new FileOutputStream(this.path + maximo + ".txt");
		fos.write(ristra.getBytes());
		fos.close();
	}

	@Override
	public void update() throws Exception {
		String fileName=this.path + "tablero" + this.tablero.getId() + ".txt";
		FileOutputStream fos=new FileOutputStream(fileName);
		fos.write(this.tablero.getRistra().getBytes());
		fos.close();
	}

	@Override
	public Vector<String> getTableros(String tipo) {
		Vector<String> result=new Vector<String>();
		FiltroFicheros filtro=new FiltroFicheros();
		Vector<String> ficheros=filtro.loadFiles(this.path);
		for (String s : ficheros) {
			String sNumero=s.substring(6, s.indexOf("."));
			result.add(sNumero);
		}
		return result;
	}

}
